package com.station.server.entity;

import com.station.client.proxies.PBaseEntity;
import com.station.server.CustomEntityManager;

import javax.persistence.*;
import javax.persistence.criteria.*;
import java.io.*;
import java.util.List;

/**
 * User: JinJavaMojo
 * Date: 25.09.13
 */

@MappedSuperclass
public abstract class BaseEntity {

    @Id
    public Long id;

    public static Object getInstance(PBaseEntity pBaseEntity, Class entityClass) {
        EntityManager manager = CustomEntityManager.getManager();
        CriteriaBuilder b = manager.getCriteriaBuilder();
        CriteriaQuery q = b.createQuery(entityClass);
        Root entityRoot = q.from(entityClass);
        Expression<String> name = entityRoot.get("id");
        q.select(entityRoot).where(b.equal(name,pBaseEntity.id));
        List<Object> list = manager.createQuery(q).getResultList();
        Object entity;
        if (!list.isEmpty())
            entity = list.get(0);
        else {
            try {
                entity = entityClass.newInstance();
                ((BaseEntity)entity).setNextId();
            } catch (Exception e) {
                throw new RuntimeException(e);

            }
        }
        return entity;
    }

    public void persist() {
        EntityManager manager = CustomEntityManager.getManager();
        manager.getTransaction().begin();
        manager.persist(this);
        manager.getTransaction().commit();
    }

    public void setNextId() {
        try {
            String fileName = System.getenv("TEMP") + "/Ids.txt";
            File ids = new File(fileName);
            if (!ids.exists()) {
                ids.createNewFile();
                Writer wr = new FileWriter(fileName);
                wr.write("1");
                wr.close();
                id = 0l;
            } else {
                FileReader inputFil = new FileReader(fileName);
                BufferedReader in = new BufferedReader(inputFil);
                Long nextId = Long.parseLong(in.readLine());
                id = nextId;
                nextId++;
                Writer wr = new FileWriter(fileName);
                wr.write(String.valueOf(nextId));
                wr.close();
                inputFil.close();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
